<script lang="ts">
import { CreateElement } from 'vue'
import { Component, Emit, Prop, Ref, Vue } from 'vue-property-decorator'

@Component
export default class RemoteScript extends Vue {
  @Prop(String) src!: string

  @Prop(String) id!: string

  @Emit() load (e?: Event) {}

  @Emit() error (e: Event) {}

  render (h: CreateElement) {
    if (this.id && document.getElementById(this.id)) {
      this.load()
      return h('div')
    }
    const vm = this
    return h('script', {
      attrs: {
        type: 'text/javascript',
        src: this.src,
        id: this.id
      },
      on: {
        load: (e: Event) => {
          this.load(e)
        },
        error: (e: Event) => {
          this.error(e)
        },
        readystatechange: function (e: Event) {
          if ((this as any).readyState === 'complete') {
            vm.load(e)
          }
        }
      }
    })
  }
}
</script>
